package cn.itcast.order.service;

import cn.itcast.order.clients.UserClient;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;
import cn.itcast.order.pojo.User;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserClient userClient;

    /**
     * TODO 使用Feign客户端来远程调用
     * @param orderId
     * @return
     */
    public Order queryOrderById(Long orderId) {

        // 1.查询订单
        Order order = orderMapper.findById(orderId);

        //2.使用Feign客户端来远程调用
        User user = userClient.findById(order.getUserId());

        //3.封装user到order
        order.setUser(user);

        // 4.返回
        return order;
    }

//    @Autowired
//    private RestTemplate restTemplate;
//
//    public Order queryOrderById(Long orderId) {
//
//        // 1.查询订单
//        Order order = orderMapper.findById(orderId);
//
//        //2.利用RestTemplate发送http请求,查询用户
//        //2.1 url路径
//        String url = "http://userservice/user/" + order.getUserId();
//
//        //2.2发送http请求，完成远程调用
//        User user = restTemplate.getForObject(url, User.class);
//
//        //3.封装user到order
//        order.setUser(user);
//        // 4.返回
//        return order;
//    }

    /**
     * Sentinel默认只标记Controller中的方法为资源，
     * 如果要标记其他方法，需要理由@SentinelResource
     */
    @SentinelResource(value = "goods",fallback = "queryGoodsFallback",blockHandler = "queryGoodsBlockHandler")
    public void queryGoods(){

        System.err.println("查询商品！");
    }

    public void queryGoodsBlockHandler(Integer id,
                                         BlockException e){

        System.out.println("queryGoodsBlockHandler");

        e.printStackTrace();


    }

    public void queryGoodsFallback(Integer id,
                                         Throwable throwable){

        System.out.println("queryGoodsFallback");

        System.out.println("服务出现异常,异常信息为:"+throwable);



    }
}
